<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #box {
        position: absolute;
        top: 20px;
        left: 100px;
        padding: 0;
        margin: 0;
        width: 100px;
        height: 100px;
        border: 1px solid red;
      }
    </style>
  </head>
  <body>
    <div id="box"></div>
    <script>
      var box = document.getElementById('box');
      function animate(ele, styleObj, duration) {
        var timer = 20;
        var stepTotal = duration / timer;
        var regionCss = {};
        count = 0;
        var clock;
        for (var key in styleObj) {
          regionCss[key] = parseInt(window.getComputedStyle(ele, null)[key]);
          // console.log(regionCss[key])
        }

        clock = setInterval(function () {
          count++;
          for (var key in styleObj) {
            moveStep = parseInt(styleObj[key] - regionCss[key]) / stepTotal;
              console.log(moveStep)
            //开始移动
            ele.style[key] = count * moveStep + regionCss[key] + 'px';
            // console.log(ele.style[key]);
          }
          if (count >= stepTotal) {
            clearInterval(clock);
            for (var key in styleObj) {
              ele.style[key] = styleObj[key] + 'px';
            }
          }
        }, timer);
      }
      box.addEventListener('click', function () {
        animate(box, { left: 300,top :0 }, 2000);
      });
    </script>
  </body>
</html>
